var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');
// var { usersModel, dao1Model, dao2Model,bumenModel,peopleModel } = require('../model/model')

/* GET users listing. */
router.get('/getlist', async function (req, res, next) {
  let userslist = await usersModel.find()
  // let daolist = await dao2Model.find().populate('dao1cid')

  let daolist=await dao1Model.aggregate([
    {
      $lookup: {
        from: "dao2",
        localField: "_id",
        foreignField: "dao1cid",
        as: "chindren"
      }
    },
    // {
    //   $unwind: "$dao2s"
    // },
   
  ])
  let bumen = await bumenModel.find()
  let peolist = await peopleModel.find().populate('bumencid')
  console.log(userslist, daolist, bumen);
  res.send({
    code:200,
    userslist, daolist, bumen,peolist
  })

});

// 添加
router.post('/addinfo',(req,res)=>{
  console.log(req.body);
  let a=req.body
  peopleModel.create({
    name:a.name,
    bumencid:a.cid,
    tel:a.tel,
   }
    
  )
  res.send({
    code:200,
    msg:'添加成功'
  })
})
// 无限极
router.get('/getdao', async function (req, res, next) {
  let params = req.query
  let roleinfo = await RoleModel.find({ _id: params.roleid })
  let xuanmenu = roleinfo[0]['menuid']
  // console.log(roleinfo,'roleinfo');
  let menu = await MenuModel.find({ _id: xuanmenu }).lean()
  // console.log(menu, 'menu');
  let obj = {}
  menu.forEach(item => {
    obj[item['_id']] = item
  })
  let resarr = []
  menu.forEach(item => {
    if (!item['pid']) resarr.push(item)
    if (obj[item['pid']] && !obj[item['pid']]['children']) {
      obj[item['pid']]['children'] = []
    }
    if (obj[item['pid']]) {
      obj[item['pid']]['children'].push(item)
    }
  })
  resarr=resarr.sort((a,b)=>{
    return a.idd-b.idd
  })
  res.send({
    code: 200,
    resarr,roleinfo,
  })
})
/* 登录 */
router.get('/login', async function (req, res, next) {
  let body = req.query
  // console.log(body, '登录获取的信息');

  let user = await UserModel.find({ username: body.username, password: body.password })
  // console.log(user, '2222222222222222');
  if (user.length > 0) {
    let token = "Bearer " + jwt.sign({ name: body.name }, '123', { expiresIn: '1h' })
    // console.log(token, 'token');
    res.send({
      code: 200, token, roleid: user[0].roleid,username:user[0].username
    })
  }else{ 
    res.send({
      code: 400
    })
  }
})

// 上传图片
router.post('/uploadImg', function (req, res) {
  var form = new multiparty.Form();
  form.uploadDir = 'upload'; // 设置上传图片的保存路径
  form.parse(req, function (err, fields, imgdata) {
    res.send({
      code: 200,
      img: 'http://localhost:3000/' + imgdata.file[0].path
    })
  })
})
// 批量上传
router.post('/uploadexel', (req, res, next) => {
  let form = new multiparty.Form();
  form.uploadDir = 'upload'
  form.parse(req, (err, fields, files) => {
    let [{ data }] = xlsx.parse(files.file[0].path);
    console.log(data);
    data.shift()
    let list = []
    data.forEach((item) => {
      list.push({
        cid: item[0],
        id: item[1],
        title: item[2],
        img: item[3],
        age: item[4],
      })
    })
    // console.log(res);
    let stus = JSON.parse(fs.readFileSync("data.json"))
    stus = [...stus, ...list]
    fs.writeFileSync("data.json", JSON.stringify(stus))
    res.send({
      code: 200,
      msg: "批量上传成功",
    })
  })
})
module.exports = router;
